package com.qiuyang.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //shiroFliterFacoryBean
    @Bean
    public ShiroFilterFactoryBean getFilterFactoryBean(@Qualifier("getWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        //添加过滤器
//        anon:无需认证
//        authc:必须认证
//        user：必须拥有 记住我功能才能用
//        perms：用于某个资源的权限才能访问
//        role：拥有某个角色权限
        Map<String,String> filterMap = new LinkedHashMap<>();
        filterMap.put("/admin/*","perms[user:all]");
        filterMap.put("/login","anon");
//        filterMap.put("/loginout","logout");
        //设置登录的请求
        bean.setLoginUrl("/admin");
        //未授权
        bean.setUnauthorizedUrl("/noauth");


        bean.setFilterChainDefinitionMap(filterMap);

        return bean;
    }

    //defaultWebSercurityManager
    @Bean(name ="getWebSecurityManager")
    public DefaultWebSecurityManager getWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联Realm
        securityManager.setRealm(userRealm);
        return securityManager;
    }


    //realm
    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }


    //整合thymeleaf
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

}
